/**
 * Dear programmer:
 * When I wrote this code, only god and I knew how it worked.
 * Now, only god knows it!
 *
 * @author: Pegasus  Date: 2018-12-16 Time: 17:25
 *
 * 新建报修工单 => 上传图片
 */

import React, {Component} from 'react';
import {
    SafeAreaView,
    StyleSheet,
    View,
    TouchableOpacity,
    Text,
    Modal,
    ScrollView, Image,
    Dimensions,
    ToastAndroid, TouchableHighlight
} from 'react-native';

import {connect} from 'react-redux';
import ActionSheet from 'react-native-actionsheet'
import ImageViewer from 'react-native-image-zoom-viewer'
import {SCREEN_HEIGHT, SCREEN_WIDTH} from "../../../../constant/PHScreen"
import {COLOR_GRAY_LINE} from "../../../../constant/PHColors"
import AntDesign from "react-native-vector-icons/AntDesign"
import BottomButtonView from "../../../../component/BottomButtonView/BottomButtonView"
import ImagePicker from "react-native-image-crop-picker"
import {getStore} from "../../../../configuration/StoreConfiguration";
import global from "../../../../configuration/global";
import {AppRequestPath} from "../../../../configuration/AppConfig";
import {API_UPLOADIMG} from "../../../../constant/API";
import User from "../../../../model/User/User"

class RepairWorkOrderUploadImageScreen extends Component {

  static navigationOptions = {
    title: '选择图片'
  }

    //构造
    constructor(props) {
        super(props);

        let {imageArr} = this.props.navigation.state.params;
        this.state = {
            clickNum:0,
            showBigPicIndex:1,
            imageArr:imageArr||[{},{},{},{},{}], //图片数组
            showBigPicModal:false,//查看大图modal
            showBigPicUrlArr:[],//查看大图url
        }
    }

  render() {
    return (
      <SafeAreaView style={{flex: 1}}>

        <ScrollView style={{flex: 1}}>

          <View style={{flexDirection: 'row', flexWrap: 'wrap'}}>
            {
              this.state.imageArr.map((item, index) => {
                return this._renderItem(item, index)
              })
            }
          </View>

        </ScrollView>

        <BottomButtonView title={'完成'} onSubmitClick={() => {

            let imageArr=this.state.imageArr;
            let token = getStore().getState().onToken;
            User.getUser(user => {
                let lastIndex=0;
                for (let i = 0; i < imageArr.length; i++) {
                    if(imageArr[i]["size"]){
                        lastIndex=i;
                    }
                }
                for (let i = 0; i < imageArr.length; i++) {
                    if(imageArr[i]["size"]){
                        let file = { uri: imageArr[i]['path'], type: "multipart/form-data", name: "image."+imageArr[i]['mime'].split("/")[1] };
                        let data = new FormData();
                        data.append('imgFile', file);
                        data.append("token", token);
                        data.append("hotelId", user.hotelId);
                        try {
                            fetch(AppRequestPath()+ API_UPLOADIMG, {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'multipart/form-data;charset=utf-8'
                                },
                                body: data
                            }).then(function(response) {
                                return response.json();
                            }).then(data=>{
                                imageArr[i]['path']=data["url"];
                                if(imageArr[i]['localImg'])
                                    delete imageArr[i]['localImg']
                                if(lastIndex==i){
                                    ToastAndroid.show('上传成功', 1000);
                                    // this.props.navigation.goBack(imageArr);
                                    this.props.navigation.state.params.goBack(imageArr);
                                }
                            })
                        } catch (err) {
                            console.log(err)
                        }
                    }
                }

            })
        }}/>

        <ActionSheet
          ref={o => this.ActionSheet = o}
          title={'选择图片'}
          options={['查看','相册', '拍照', '取消']}
          cancelButtonIndex={3}
          onPress={(index) => {
            switch (index) {
                case 0: {
                    console.log(JSON.stringify(this.state.imageArr))
                    let index = this.state.clickNum;
                    // this.state.showBigPicUrl = this.state.imageArr[index]['path'];

                    let showBigPicUrlArr = []

                    for (let i = 0; i < this.state.imageArr.length; i++){
                        let showBigPicUrl = {}
                        if(this.state.imageArr[i]['path']){
                            if(this.state.imageArr[i]['localImg']){
                                showBigPicUrl = {url:this.state.imageArr[i]['path']}
                            }else{
                                showBigPicUrl = {url:AppRequestPath()+"/img/"+global.hotelId+"/"+this.state.imageArr[i]['path']}
                            }
                            showBigPicUrlArr.push(showBigPicUrl)
                        }
                    }
                    console.log(JSON.stringify(showBigPicUrlArr))

                    if(this.state.imageArr[index]['path']){
                        this.setState({
                            showBigPicIndex:index,
                            showBigPicUrlArr:showBigPicUrlArr,
                            showBigPicModal:true
                        })
                    }else{
                        ToastAndroid.show('请先添加图片！', 1000);
                    }


                    break;
                }
              case 1: {
                ImagePicker.openPicker({
                  multiple: true
                }).then(images => {
                  //console.log(images,this.state.clickNum);
                  let arr = this.state.imageArr;
                  images[0].localImg=1;
                  arr[this.state.clickNum] = images[0];
                  this.setState({
                      imageArr : arr,
                  })
                });
                break;
              }
              case 2: {
                ImagePicker.openCamera({
                  width: 400,
                  height: 300,
                  cropping: true
                }).then(image => {
                    let arr = this.state.imageArr;
                    image.localImg=1;
                    arr[this.state.clickNum] = image;
                    this.setState({
                        imageArr : arr,
                    })
                });
                break;
              }
              default: {
                break;
              }
            }
          }}
        />

          {/*查看大图*/}
          <Modal
              visible={this.state.showBigPicModal}
              //显示是的动画默认none
              //从下面向上滑动slide
              //慢慢显示fade
              animationType = {'slide'}
              //是否透明默认是不透明 false
              transparent = {true}
              //关闭时调用
              // onRequestClose={()=> this.onRequestClose()}
          >
              <View style={{flex: 1, backgroundColor: '#000'}} >
                  <View style={{alignItems:'center',justifyContent:'center',flexDirection:'column',width:SCREEN_WIDTH,height:SCREEN_HEIGHT}} >
                      {/*<Image source={{uri:this.state.showBigPicUrl}}  style={{width: SCREEN_WIDTH , height:SCREEN_WIDTH-20,}} />*/}

                      <ImageViewer
                          imageUrls={this.state.showBigPicUrlArr} // 照片路径
                          index={this.state.showBigPicIndex}
                          enableImageZoom={true} // 是否开启手势缩放
                          style={{width: SCREEN_WIDTH, height: SCREEN_WIDTH-20}}
                          enableSwipeDown={false}
                          onChange={(index) => { }} // 图片切换时触发
                          onClick={() => { // 图片单击事件
                              this.onRequestClose()
                          }}
                      />
                  </View>
              </View>
          </Modal>

      </SafeAreaView>
    )
  }


    onRequestClose(){
        this.setState({
            showBigPicModal: false,
        })
    }

  _renderItem(item, index) {
    return (
      <View key={index} style={{width: SCREEN_WIDTH / 3, height: SCREEN_WIDTH / 3, justifyContent: 'center', alignItems: 'center'}}>
        <TouchableOpacity key={index} activeOpacity={0.8} onPress={() => {
            this.state.clickNum = index;
          this.ActionSheet.show();
        }}>
            {/*{
                this.state.imageArr[index]['path'] ? (
                    <Image source={{uri:this.state.imageArr[index]['path']}}  style={{width: SCREEN_WIDTH / 3 - 30, height: SCREEN_WIDTH / 3 - 30,}} />
                ) : (
                    <View
                        key={index}
                        style={{
                            margin: 15,
                            width: SCREEN_WIDTH / 3 - 30,
                            height: SCREEN_WIDTH / 3 - 30,
                            borderRadius: 10,
                            borderColor: COLOR_GRAY_LINE,
                            borderWidth: 1,
                            justifyContent: 'center',
                            alignItems: 'center'
                        }}>
                        <AntDesign name={'plus'} size={40} style={{color: COLOR_GRAY_LINE}}/>
                    </View>
                )
            }*/}
          <View
            key={index}
            style={{
              margin: 15,
              width: SCREEN_WIDTH / 3 - 30,
              height: SCREEN_WIDTH / 3 - 30,
              borderRadius: 10,
              borderColor: COLOR_GRAY_LINE,
              borderWidth: 1,
              justifyContent: 'center',
              alignItems: 'center'
            }}>
              {
                this.state.imageArr[index]['path'] ? (
                    (this.state.imageArr[index]['localImg'] ?
                        <Image source={{uri:this.state.imageArr[index]['path']}}  style={{width: SCREEN_WIDTH / 3 - 30, height: SCREEN_WIDTH / 3 - 30}} />:
                        <Image source={{uri:AppRequestPath()+"/img/"+global.hotelId+"/"+this.state.imageArr[index]['path']}}  style={{width: SCREEN_WIDTH / 3 - 30, height: SCREEN_WIDTH / 3 - 30}} />
                    )) : (
                        <AntDesign name={'plus'} size={40} style={{color: COLOR_GRAY_LINE}}/>
                )
              }
          </View>


        </TouchableOpacity>

        <View style={{position: 'absolute', width: 20, height: 20}}>

        </View>
      </View>
    )
  }

  _onSubmitClick() {

  }

  _showActionSheet = () => {
    this.ActionSheet.show()
  }

}

const props = state => {
  return {}
}

export default RepairWorkOrderUploadImageScreen = connect(props)(RepairWorkOrderUploadImageScreen);

const styles = StyleSheet.create({})